<script setup lang="ts">
import { ref, onMounted } from 'vue'
import NavBar from '../components/NavBar.vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
interface Post {
  id: number
  title: string
  image: string
  author: {
    name: string
    avatar: string
  }
  likes: number
  shares: number
  isLiked: boolean
  isRequesting: boolean // 新增标志位，用于避免重复请求
  isShared: boolean
}
const posts = ref<Post[]>([])
const isPostsFetched = ref(false) // 标志位，判断是否已经获取过帖子数据

// 从 localStorage 中获取点赞状态
const getLikedStatusFromStorage = (postId: number) => {
  const likedStatus = localStorage.getItem(`post_${postId}_liked`)
  return likedStatus ? JSON.parse(likedStatus) : false
}
// 将点赞状态保存到 localStorage
const saveLikedStatusToStorage = (postId: number, isLiked: boolean) => {
  localStorage.setItem(`post_${postId}_liked`, JSON.stringify(isLiked))
}

// 从 localStorage 中获取分享状态
const getSharedStatusFromStorage = (postId: number) => {
  const sharedStatus = localStorage.getItem(`post_${postId}_shared`)
  return sharedStatus ? JSON.parse(sharedStatus) : false
}

// 将分享状态保存到 localStorage
const saveSharedStatusToStorage = (postId: number, isShared: boolean) => {
  localStorage.setItem(`post_${postId}_shared`, JSON.stringify(isShared))
}



const fetchPosts = async () => {
  if (isPostsFetched.value) return
  try {
    const response = await axios.get('http://localhost:10086/commity/community-content/getAllContent');
    posts.value = response.data.map((content: any) => ({
      id: content.contentId,
      title: content.title,
      image: content.imageUrl,
      author: {
        name: content.nickname,
        avatar: content.avatar,
      },
      likes: content.likeCount,
      shares: content.shareCount ,
      isLiked: getLikedStatusFromStorage(content.contentId), // 从 localStorage 读取点赞状态
      isRequesting: false,
      isShared: getSharedStatusFromStorage(content.contentId) // 从 localStorage 读取分享状态
    }));
    isPostsFetched.value = true // 标记为已经获取过数据
  } catch (error) {
    console.error('Error fetching posts:', error);
  }
};
const goToProfile = (userId: number) => {
  router.push({
    name: 'Author',
    params: {
      id: userId
      // nickname: author.name,
      // avatar: author.avatar
    }
  })
}
const likePost = async (post: Post) => {
  if (post.isRequesting) return // 如果正在请求，直接返回
  post.isRequesting = true // 设置请求状态为 true
  try {
    let response
    if (post.isLiked) {
      // 取消点赞
      response = await axios.get(`http://localhost:10086/commity/community-content/unlikeContent/${post.id}`)
    } else {
      // 点赞
      response = await axios.get(`http://localhost:10086/commity/community-content/likeContent/${post.id}`)
    }
    // 假设后端成功返回的状态码是 200
    if (response.status === 200) {
      if (post.isLiked) {
        post.likes--
        post.isLiked = false
      } else {
        post.likes++
        post.isLiked = true
      }
      // 保存点赞状态到 localStorage
      saveLikedStatusToStorage(post.id, post.isLiked)
    }
  } catch (error) {
    console.error('点赞/取消点赞失败:', error)
  } finally {
    post.isRequesting = false // 请求结束，设置请求状态为 false
  }
}

const sharePost = async (post: Post) => {
  if (post.isRequesting) return
  post.isRequesting = true
  try {
    let response
    if (post.isShared) {
      // 取消分享
      response = await axios.get(`http://localhost:10086/commity/community-content/unshareContent/${post.id}`)
    } else {
      // 分享
      response = await axios.get(`http://localhost:10086/commity/community-content/shareContent/${post.id}`)
    }
    // 假设后端成功返回的状态码是 200
    if (response.status === 200) {
      if (post.isShared) {
        post.shares--
        post.isShared = false
      } else {
        post.shares++
        post.isShared = true
      }
      // 保存分享状态到 localStorage
      saveSharedStatusToStorage(post.id, post.isShared)
    }
  } catch (error) {
    console.error('分享/取消分享失败:', error)
  } finally {
    post.isRequesting = false
  }
}



onMounted(() => {
  fetchPosts();
});
const goToWorkDetail = (workId: number) => {
  router.push({
    name: 'WorkDetail',
    params: { id: workId }
  });
};
interface Dialog {
  image: string
  // title: string
  startTime: string
  description: string
}

// 将 showPublishModal 定义为一个响应式引用
const showPublishModal = ref(false);

const togglePublishModal = () => {
  showPublishModal.value = !showPublishModal.value;
};
const dialogList = [
  {
    image: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.lhibvaCdwSnTxWVg7ykIkQHaHa?rs=1&pid=ImgDetMain',
    // title: '对话武则天',
    startTime: '2022-01-01 11:00:25',
    description: '帮我画一副孙悟空腾云驾雾的画...'
  },
];
const toDuiHua = () => {

  router.push({ name: 'HistoryChat', query: { from: 'community' } })

}
</script>
<template>
  <div class="community-container">
    <NavBar />

    <div class="posts-grid">
      <div v-for="post in posts" :key="post.id" class="post-card">
        <div @click="goToWorkDetail(post.id)">
          <div class="post-image">
            <img :src="post.image" :alt="post.title">
          </div>
          <h3 class="post-title">{{ post.title }}</h3>
        </div>
        <div class="post-content">
          <div class="post-footer">
            <div class="author" @click="goToProfile(post.id)">
              <img :src="post.author.avatar" :alt="post.author.name" class="author-avatar">
              <span class="author-name">{{ post.author.name }}</span>
            </div>
            <div class="actions">
              <div class="action-item" @click="likePost(post)">
                <i :class="['like-icon', { 'liked': post.isLiked }]"></i>
                <span>{{ post.likes }}</span>
              </div>
              <div class="action-item" @click="sharePost(post)">
                <i :class="['share-icon', { 'shared': post.isShared }]"></i>
                <span>{{ post.shares }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <button class="create-post-btn" @click="togglePublishModal">
      <i class="create-icon"></i>
      发布作品
    </button>
    <!-- 发布作品遮罩弹框 -->
    <div v-if="showPublishModal" class="publish-modal">
      <div class="modal-content">
        <!-- 这里添加弹框的具体内容，比如表单等 -->
        <center>
          <b>选择AI历史对话发布作品</b>
        </center>
        <div class="dialog-list">
          <div v-for="(dialog, index) in dialogList" :key="index" class="dialog-item" @click="toDuiHua">
            <img :src="dialog.image" class="dialog-image">
            <div class="dialog-info">
              <p class="dialog-description">{{ dialog.description }}</p>
              <p class="dialog-time">{{ dialog.startTime }}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-mask" @click="togglePublishModal"></div>
    </div>
  </div>
</template>
<style scoped>
.community-container {
  padding-top: 84px;
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

.posts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 12px;
}

.post-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.post-image {
  position: relative;
  width: 100%;
  padding-top: 100%;
  /* 1:1 aspect ratio */
}

.post-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.ai-tag {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.post-content {
  padding: 12px;
}

.post-title {
  margin: 0;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.author:hover {
  opacity: 0.8;
}

.author-avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  object-fit: cover;
}

.author-name {
  font-size: 12px;
  color: #666;
}

.actions {
  display: flex;
  gap: 12px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 12px;
}

.like-icon,
.share-icon {
  width: 15px;
  height: 15px;
  background-size: contain;
  background-repeat: no-repeat;
}

.create-post-btn {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #007AFF;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
}

.create-icon {
  width: 16px;
  height: 16px;
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="%23fff" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>');
  background-size: contain;
}
.like-icon {
  width: 15px;
  height: 15px;
  background-size: contain;
  background-repeat: no-repeat;
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="%23666" d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>');
}

.liked {
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="red" d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>');
}
.share-icon {
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="%23666" d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92-1.31-2.92-2.92-2.92z"/></svg>');
}

.shared {
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="blue" d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0.24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92-1.31-2.92-2.92-2.92z"/></svg>');
}

.publish-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 65%;
  border-top-left-radius: 30px;
  border-top-right-radius: 30px;
  background-color: rgba(255, 255, 255);
  border-top: 2px solid #007bffb1;
  /* display: flex; */
  /* justify-content: center;
    align-items: center; */
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 80%;
  max-width: 500px;
}

/* .modal-mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 65%;
    background-color: rgba(255, 255, 255);
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
} */
.dialog-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  /* align-items: center; */
  margin: 10px;
  border-radius: 10px;
  background-color: #f5f5f5;
}

.dialog-info {
  width: 75%;
  height: 100%;
  /* background: #f5070750; */
}

.dialog-image {
  width: 25%;
  height: 100%;
  border-radius: 15%;
  object-fit: cover;
  margin-right: 10px;
  overflow: hidden;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
</style>
